package dobest.ray.com.jiongjiong.activity.mumingleshi;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dobest.ray.corelibs.utils.ToastMgr;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import dobest.ray.com.jiongjiong.R;
import dobest.ray.com.jiongjiong.activity.BaseActivity;
import dobest.ray.com.jiongjiong.bean.BindDeviceBean;
import dobest.ray.com.jiongjiong.utils.ACacheHelper;
import dobest.ray.com.jiongjiong.views.ColorfulRingProgressView;
import dobest.ray.com.jiongjiong.views.chart.HoriScrollMMLSView;

/**
 * Created by Ray on 2016/3/11.
 * https://github.com/ray0807
 */
public class MumingleshiActivity extends BaseActivity implements ColorfulRingProgressView.ProgressTextCallback, View.OnClickListener {

    private ColorfulRingProgressView crpv;
    private TextView tv_score;
    private HoriScrollMMLSView scrollMMLSView;


    private static final int CONNECTING = 100;
    private static final int SCAN = 99;
    private static final int CONNECTED = 101;
    private static final int UNBIND = 102;
    private static final int CONNECTED_FAILED = 103;
    private static final int DISCONNECTED = 104;
    private TextView tv_title;


    private Button btn_1;
    private Button btn_2;
    private Button btn_3;

    /**
     * 一分钟训练数据1
     */
    private static final String ONE_MIN_DATAS_TAG1 = "AA 01 FE 01 01";
    /**
     * 一分钟训练数据2
     */
    private static final String ONE_MIN_DATAS_TAG2 = "AA 01 FE 01 02";


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    tv_score.setText(msg.obj.toString());
                    break;
                case SCAN:
                    tv_title.setText("正在搜索绑定的设备...");
                    break;
                case CONNECTING:
                    tv_title.setText("正在连接...");
                    break;
                case CONNECTED:
                    tv_title.setText("目明乐视（已连接）");
                    break;
                case CONNECTED_FAILED:
                    tv_title.setText("目明乐视（连接失败）");

                    //连接失败重新扫描
                    handler.sendEmptyMessage(SCAN);
                    bluetoothAdapter.startLeScan(mLeScanCallback);
                    break;
                case DISCONNECTED:
                    tv_title.setText("目明乐视（已断开）");
                    break;
                case UNBIND:
                    tv_title.setText("目明乐视（未绑定）");
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mumingleshi);
        findViews();
        init();
        addListeners();
        initBle();
    }


    @Override
    public void findViews() {
        crpv = (ColorfulRingProgressView) findViewById(R.id.crpv);
        tv_score = (TextView) findViewById(R.id.tv_score);
        tv_title = (TextView) findViewById(R.id.tv_title);
        scrollMMLSView = (HoriScrollMMLSView) findViewById(R.id.hsmmlsv_bar);

        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);
        btn_3 = (Button) findViewById(R.id.btn_3);
    }

    @Override
    public void init() {

        crpv.setPercent(75);
        crpv.setStartAngle(0);
        crpv.setBackgroundColor(Color.parseColor("#00b9a9"));
        crpv.setProgressCallback(this);
        crpv.setPercent(80);
        //设置测试数据
        scrollMMLSView.setData();
    }

    @Override
    public void addListeners() {
        btn_1.setOnClickListener(this);
        btn_2.setOnClickListener(this);
        btn_3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_1:
                getDeviceOneMinData();
                break;
            case R.id.btn_2:
                getDeviceAllData();
                break;
            case R.id.btn_3:
                getSynchronizationTime();
                break;
        }

    }

    @Override
    public void callbackProgress(int pregress) {
        Message msg = Message.obtain();
        msg.what = 1;
        msg.obj = pregress;
        handler.sendMessage(msg);
    }


    /**
     * 蓝牙相关
     */
    private BluetoothLeService mBluetoothLeService;
    private String mDeviceName;
    private String mDeviceAddress;
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    private BluetoothGattCharacteristic mNotifyCharacteristic;
    private final String LIST_NAME = "NAME";
    private final String LIST_UUID = "UUID";
    private Intent gattServiceIntent;
    private BluetoothAdapter bluetoothAdapter;
    private ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
    private PopupWindow pw;
    private boolean isBindServiece = false;
    private BindDeviceBean bean;

    private void initBle() {
        gattServiceIntent = new Intent(this, BluetoothLeService.class);
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            ToastMgr.show("不支持蓝牙");
        }

        // 获得蓝牙管理器
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter != null) {
            if (!bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.enable();
            }
        }

        bean = ACacheHelper.getInstance().getBindDevices(MumingleshiActivity.this);
        handler.sendEmptyMessage(SCAN);
        bluetoothAdapter.startLeScan(mLeScanCallback);
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter
                .addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 扫描到后添加然后刷新
                    if (bean != null && device.getName().equals(bean.deviceName) && device.getAddress().equals(bean.deviceMac)) {
                        handler.sendEmptyMessage(CONNECTING);
                        bluetoothAdapter.stopLeScan(mLeScanCallback);
                        mDeviceName = device.getName();
                        mDeviceAddress = device.getAddress();
                        bindService(gattServiceIntent, mServiceConnection,
                                BIND_AUTO_CREATE);
                        if (mBluetoothLeService != null) {
                            final boolean result = mBluetoothLeService
                                    .connect(mDeviceAddress);
                        }
                    } else {
                        handler.sendEmptyMessage(UNBIND);
                    }
                }
            });
        }
    };


    // 服务链接
    ServiceConnection mServiceConnection = new ServiceConnection() {

        // 链接服务
        @Override
        public void onServiceConnected(ComponentName componentName,
                                       IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                    .getService();
            if (!mBluetoothLeService.initialize()) {
                finish();
            }

            isBindServiece = true;
            // 链接设备
            boolean flag = mBluetoothLeService.connect(mDeviceAddress);
            if (flag) {
                ToastMgr.show("链接成功");
            } else {
                handler.sendEmptyMessage(CONNECTED_FAILED);
            }
        }

        // 断开服务
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
            ToastMgr.show("断开连接");
            handler.sendEmptyMessage(DISCONNECTED);
            isBindServiece = false;
        }
    };

    // 广播接受 者
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            // 如果已经链接了
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                ToastMgr.show("连接成功");
                handler.sendEmptyMessage(CONNECTED);

                // 如果没有链接
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
                    .equals(action)) {
                handler.sendEmptyMessage(CONNECTED_FAILED);
                ToastMgr.show("连接失败");

                // 如果发现服务
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
                    .equals(action)) {
                displayGattServices(mBluetoothLeService
                        .getSupportedGattServices());
                //发送指令
                getStartData();


                // 有用的数据
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                String str = intent
                        .getStringExtra(BluetoothLeService.EXTRA_DATA);
                int index = str.indexOf("A", 1);
                //真正的返回数据
                String RStr = str.substring(index);
                String[] stringByte = str.split(" ");
                Log.i("wanglei", "设备电量--------");
                if (stringByte.length == 20) {
                    //接收蓝牙设备返回数据
                    Log.i("wanglei", "返回数据：" + RStr);
                }
            }
        }
    };

    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null)
            return;
        String uuid = null;
        String unknownServiceString = getResources().getString(
                R.string.unknown_service);
        String unknownCharaString = getResources().getString(
                R.string.unknown_characteristic);
        ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData = new HashMap<String, String>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(LIST_NAME,
                    SampleGattAttributes.lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService
                    .getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();

            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData = new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put(LIST_NAME,
                        SampleGattAttributes.lookup(uuid, unknownCharaString));
                currentCharaData.put(LIST_UUID, uuid);
                gattCharacteristicGroupData.add(currentCharaData);
            }
            mGattCharacteristics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mGattUpdateReceiver);
        bluetoothAdapter.stopLeScan(mLeScanCallback);
//        bluetoothAdapter.disable();
        if (isBindServiece) {
            unbindService(mServiceConnection);
        }
        mBluetoothLeService = null;
        super.onDestroy();
    }


    /**
     * 获取设备当前时间
     */
    private void getDeviceCurrentTime() {
        byte[] buffer = new byte[4];
        buffer[0] = (byte) 0xAA;
        buffer[1] = (byte) 0x01;
        buffer[2] = (byte) 0xF9;
        buffer[3] = (byte) 0x00;
        mBluetoothLeService.writeLlsAlertLevel(2, buffer);
    }

    /**
     * 获取设备电量
     */
    private void getDeviceBattery() {
        byte[] buffer = new byte[4];
        buffer[0] = (byte) 0xAA;
        buffer[1] = (byte) 0x01;
        buffer[2] = (byte) 0xF4;
        buffer[3] = (byte) 0x00;
        mBluetoothLeService.writeLlsAlertLevel(2, buffer);
    }

    /**
     * 获取设备一分钟数据
     */
    private void getDeviceOneMinData() {
        byte[] buffer = new byte[5];
        buffer[0] = (byte) 0xAA;
        buffer[1] = (byte) 0x01;
        buffer[2] = (byte) 0xFE;
        buffer[3] = (byte) 0x01;
        buffer[4] = (byte) 0x01;
        mBluetoothLeService.writeLlsAlertLevel(2, buffer);
    }

    /**
     * 获取设备所有训练数据
     */
    private void getDeviceAllData() {
        byte[] buffer = new byte[4];
        buffer[0] = (byte) 0xAA;
        buffer[1] = (byte) 0x01;
        buffer[2] = (byte) 0xFC;
        buffer[3] = (byte) 0x00;
        mBluetoothLeService.writeLlsAlertLevel(2, buffer);
    }


    // 与设备时间同步
    private void getSynchronizationTime() {
        Calendar c = Calendar.getInstance();
        String year = c.get(Calendar.YEAR) + "";
        year = year.substring(year.length() - 2, year.length());
        String month = "" + (c.get(Calendar.MONTH) + 1);
        String day = "" + c.get(Calendar.DAY_OF_MONTH);
        String hour = "" + c.get(Calendar.HOUR_OF_DAY);
        String min = "" + c.get(Calendar.MINUTE);
        // AA 01 F8 05 15 07 22 17 30
        byte[] buffer = new byte[9];
        buffer[0] = (byte) 0xAA;
        buffer[1] = (byte) 0x01;
        buffer[2] = (byte) 0xF8;
        buffer[3] = (byte) 0x05;

        buffer[4] = (byte) Integer.parseInt(year, 16);//2016
        buffer[5] = (byte) Integer.parseInt(month, 16);//3
        buffer[6] = (byte) Integer.parseInt(day, 16);//8
        buffer[7] = (byte) Integer.parseInt(hour, 16);//15
        buffer[8] = (byte) Integer.parseInt(min, 16);//57
        mBluetoothLeService.writeLlsAlertLevel(2, buffer);
    }

    private void getStartData() {
        final BluetoothGattCharacteristic characteristic = mGattCharacteristics
                .get(3).get(0);
        mBluetoothLeService.setCharacteristicNotification(characteristic, true);
        mBluetoothLeService.readCharacteristic(characteristic);
        final BluetoothGattCharacteristic characteristic2 = mGattCharacteristics
                .get(3).get(0);
        mBluetoothLeService
                .setCharacteristicNotification(characteristic2, true);
        byte[] bb = new byte[40];
        bb[0] = (byte) 0xFF;
        bb[1] = (byte) 0xA0;
        bb[2] = (byte) 0xFF;
        bb[3] = (byte) 0xA0;
        bb[4] = (byte) 0xFF;
        bb[5] = (byte) 0xA0;
        bb[6] = (byte) 0xFF;
        bb[7] = (byte) 0xA0;
        bb[8] = (byte) 0xFF;
        bb[9] = (byte) 0xA0;
        bb[10] = (byte) 0xFF;
        bb[11] = (byte) 0xA0;
        bb[12] = (byte) 0xFF;
        bb[13] = (byte) 0xA0;
        bb[14] = (byte) 0xFF;
        bb[15] = (byte) 0xA0;
        bb[16] = (byte) 0xFF;
        bb[17] = (byte) 0xA0;
        bb[18] = (byte) 0xFF;
        bb[19] = (byte) 0xA0;
        bb[20] = (byte) 0xFF;
        bb[21] = (byte) 0xA0;
        bb[22] = (byte) 0xFF;
        bb[23] = (byte) 0xA0;
        bb[24] = (byte) 0xFF;
        bb[25] = (byte) 0xA0;
        bb[26] = (byte) 0xFF;
        bb[27] = (byte) 0xA0;
        bb[28] = (byte) 0xFF;
        bb[29] = (byte) 0xA0;
        bb[30] = (byte) 0xFF;
        bb[31] = (byte) 0xA0;
        bb[32] = (byte) 0xFF;
        bb[33] = (byte) 0xA0;
        bb[34] = (byte) 0xFF;
        bb[35] = (byte) 0xA0;
        bb[36] = (byte) 0xFF;
        bb[37] = (byte) 0xA0;
        bb[38] = (byte) 0xFF;
        bb[39] = (byte) 0xA0;

        mBluetoothLeService.writeLlsAlertLevel(2, bb);
    }

}
